<template>
    <div class="userList">
        <!--卡片-->
        <el-card class="box-card">


            <!--定义搜索-->
            <el-form :inline="true" :model="formData" class="demo-form-inline" @submit.native.prevent>
                <el-form-item size="mini">
                    <el-input v-model="formData.username" placeholder="请输入用户名称"
                              @keyup.enter.native="findUserBySouSuo"></el-input>
                </el-form-item>
                <el-date-picker
                        style="margin-left: 10px"
                        v-model="formData.startDate"
                        align="right"
                        type="date"
                        placeholder="选择开始日期"
                        :picker-options="startDate"
                        size="mini">
                </el-date-picker>
                <el-date-picker
                        style="margin-left: 10px"
                        v-model="formData.endDate"
                        align="right"
                        type="date"
                        placeholder="选择结束日期"
                        :picker-options="endDate"
                        size="mini">
                </el-date-picker>
                <el-form-item>
                    <el-button round type="primary" @click="findUserBySouSuo" size="mini" icon="el-icon-search"
                               style="margin-left: 10px;margin-right: 10px">搜索
                    </el-button>
                    <el-button round type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="xinzeng">
                        添加
                    </el-button>
                    <el-button type="primary" icon="el-icon-refresh" size="mini" circle
                               @click="handleReset"></el-button>
                </el-form-item>
            </el-form>

            <!--数据表格-->
            <el-table
                    :data="tableData"
                    border
                    style="width: 100%">
                <el-table-column
                        prop="headUrl"
                        width="120"
                        label="头像">
                    <template slot-scope="scope">
                        <img :src="scope.row.headUrl" width="80" height="80"/>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="username"
                        label="用户名"
                        align="center"
                        width="180">
                </el-table-column>
                <el-table-column
                        prop="nickName"
                        label="备注"
                        align="center"
                        width="180">
                </el-table-column>
                <el-table-column width="180"
                                 prop="status"
                                 align="center"
                                 label="状态">
                    <template slot-scope="scope">
                        <el-switch
                                :active-value="1"
                                :inactive-value="0"
                                v-model="scope.row.status"
                                @change="changeStatus(scope.row.id,scope.row.status)"
                                inactive-color="#13ce66"
                                active-color="#ff4949"
                                active-text="禁用"
                                inactive-text="正常">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column width="190"
                                 prop="gmtCreate"
                                 label="创建时间">
                </el-table-column>
                <el-table-column width="190"
                                 prop="gmtModified"
                                 label="修改时间">
                </el-table-column>
                <el-table-column label="操作" width="400" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" disabled v-if="scope.row.status==0" type="danger" @click="handleDelete(scope.$index, scope.row.id)">删除
                        </el-button>
                        <el-button size="mini" v-else type="danger" @click="handleDelete(scope.$index, scope.row.id)">删除</el-button>
                        <el-button size="mini" type="success" @click="fenRoleDialog(scope.row.id)">设置角色</el-button>
                        <el-button size="mini" type="danger">修改密码</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-divider><i class="el-icon-moon-night"></i></el-divider>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    style="float: right;margin-top: 20px; margin-bottom: 22px"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>


        <!--添加的弹出框表单-->
        <el-dialog :title="tableFormName"
                   @closed="flushAll"
                   width="30%"
                   :visible.sync="dialogFormVisible">
            <el-form :model="form"
                     :rules="addFormRules"
                     ref="formLabel"
                     label-width="70px"
                     @submit.native.prevent
                     class="demo-ruleForm"
            >
                <!--添加角色的弹出框表单-->

                <el-form-item prop="headUrl" label="头像">
                    <el-upload
                            class="avatar-uploader"
                            action="http://192.168.28.198:8000/home/banner/uploadMsg"
                            :show-file-list="false"
                            :headers="token"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <img style="height: 50px;width: 200px" v-if="form.headUrl" v-model="form.headUrl" :src="form.headUrl" class="avatar" alt="">
                        <i v-else  class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

                <el-form-item label="名称:" prop="username">
                    <el-input @keyup.enter.native="addUser" type="text" v-model="form.username" autocomplete="off"
                              placeholder="请输入用户名称"></el-input>
                </el-form-item>
                <el-form-item label="密码:">
                    <el-input type="text" v-model="form.password" autocomplete="off"
                              placeholder="请输入用户密码"></el-input>
                </el-form-item>
                <el-form-item label="备注:">
                    <el-input type="textarea" v-model="form.nickName" autocomplete="off"
                              placeholder="请输入角色备注"></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </div>
        </el-dialog>


        <!--修改用户信息对话框开始-->
        <el-dialog
                title="修改用户"
                :visible.sync="updateUserDialog"
                width="30%"
                @closed="closeUpdateUser"
        >
            <!--表单的数据绑定-->
            <el-form :model="updateUserFormData" @submit.native.prevent :rules="updateUserFormRule" ref="editerRef"  label-width="70px" class="demo-ruleForm">
                <el-form-item label="用户名:" prop="username">
                    <el-input disabled type="text" v-model="updateUserFormData.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="备注:">
                    <el-input type="textarea" v-model="updateUserFormData.nickName" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="updateUserDialog = false">取 消</el-button>
                <el-button type="primary" @click="updateUser">确 定</el-button>
            </span>
        </el-dialog>
        <!--修改用户信息对话框结束-->

        <!--修改角色权限开始-->
        <el-dialog
                title="修改角色权限"
                :visible.sync="dialogVisible"
                width="30%">

            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
            </el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
                <el-checkbox v-for="role in roles" :label="role.id" :key="role.id">{{ role.roleName }}</el-checkbox>
            </el-checkbox-group>
            <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="confirmFenRole">确 定</el-button>
            <el-button @click="dialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>
        <!--修改角色权限结束-->

    </div>
</template>

<script>
    export default {
        name: "UserList",
        created() {
            this.initTable();
        },
        data() {
            return {
                token:{
                    "token":sessionStorage.getItem("token")
                },
                dialogVisible: false,    //控制权限的弹框显示
                checkAll: false,    //权限是否全选
                checkedRoles: [],   //用户具有的权限
                roles: [],          //查询具有的所有权限
                allRoles: [],
                userId: "",          //用户id
                isIndeterminate: true,

                roleFormData: {  //权限搜索框的内容
                    roleName: "",
                },

                //当前页面--》page
                roleCurrentPage: 1,
                //每页几条--》limit
                rolePageSize: 5,
                //总条数
                roleAllTotal: 0,
                idlist: [],

                //新增用户的表单元素判断
                addFormRules: {
                    username: [
                        {required: true, message: '用户名不能为空'},
                        {min: 2, max: 10, message: "账号的长度[2~10]", trigger: "blur"},
                    ],
                },

                //控制修改框的是否显示
                updateUserDialog: false,
                //修改用户的表单数据
                updateUserFormData: {},
                //修改的表单校验规则
                updateUserFormRule: {},

                //当前页面--》page
                currentPage: 1,
                //每页几条--》limit
                pageSize: 5,
                //总条数
                allTotal: 0,
                tableFormName: '',
                tableData: [],
                formData: {
                    username: "",
                    startDate: '',
                    endDate: '',
                },

                //控制添加弹出对话框是否显示
                dialogFormVisible: false,
                //添加按钮弹出层表单数据
                form: {
                    username: '',
                    nickName: '',
                    password: '',
                    headUrl:''
                },
                checkedrow: [],
                startDate: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    },
                },
                endDate: {
                    disabledDate: (time) => {
                        if (this.formData.startDate != '')
                            return time.getTime() < new Date(this.formData.startDate).getTime() || time.getTime() > Date.now();
                    },
                },

            }

        },
        methods: {
            handleAvatarSuccess(res, file) {
                this.form.headUrl = res;
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //权限全选按钮
            handleCheckAllChange(val) {
                var checkedAll = this.roles.map(item => item.id)
                this.checkedRoles = val ? checkedAll : [];
                this.isIndeterminate = false;

            },
            //权限是否全选
            handleCheckedRolesChange(value) {
                let checkedCount = value.length;
                this.checkAll = checkedCount === this.roles.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length;
            },
            //点击设置角色按钮,加载所有角色及用户具有的角色
            fenRoleDialog(userId) {
                this.dialogVisible = true;
                this.userId = userId;
                this.$http.get('/system/role/getByUserId/' + this.userId).then(result => {
                    if (result.data.code === 200) {
                        this.roles = result.data.data.allRole;
                        this.checkedRoles = result.data.data.userRoleIds;
                    }
                });
            },
            //确认分配角色
            confirmFenRole() {
                const idlist = [];

                this.checkedRoles.map(item => { // 遍历获取已选中的角色id
                    idlist.push(item)
                })
                var that=this;
                this.$http.post("/system/role/confirm?userId="+this.userId+"&roleIds="+idlist).then(function (resp) {
                    if (resp.data.code === 200) {
                        that.$message.success("修改成功");
                    } else {
                        that.$message.error("修改失败");
                    }
                    that.dialogVisible = false;
                });
            },


            //关闭设置角色页面时，清空数据
            closeRoleSou() {
                this.roleFormData.roleName = "";
                this.checkedRoles = [];
                this.rolePageSize = 5;//每页几条--》limit
                this.roleCurrentPage = 1;//当前页面--》page
                this.$refs.multipleTable.clearSelection();
            },


            /*根据id删除用户
               * index:表格中的序号。。0开始
               * id:用户id
               * */
            handleDelete(index, id) {
                this.$confirm(`确定要《《彻底删除》》该用户吗?`, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var that = this;
                    this.$http.delete(`/system/user/deleteUserById/${id}`).then(function (resp) {
                        if (resp.data.code === 200) {
                            that.$message.success(resp.data.msg);
                            that.initTable();
                        } else {
                            that.$message.error(resp.data.msg);
                        }
                    })
                    this.reload()
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '删除已取消'
                    });
                })

            },

            //修改用户信息
            handleEdit(index, row) {
                this.updateUserFormData = row;//将当前行的数据放入
                this.updateUserDialog = true;//开启弹出框
            },
            //新增
            xinzeng() {
                this.tableFormName = "新增用户";
                this.dialogFormVisible = true;
                this.form = {};
            },
            //添加用户信息
            addUser() {
                var that = this;
                this.$refs.formLabel.validate((valid) => {//判断表单内是否有标红的地方
                    if (valid) {
                        this.$http.post("/system/user/addUserByUser", this.form).then(function (resp) {
                            if (resp.data.code === 200) {
                                that.$message.success(resp.data.msg);
                                that.initTable();
                                that.dialogFormVisible = false;//设置成功后关闭弹出框
                                that.flushAll();
                            } else {
                                that.$message.error(resp.data.msg);
                                that.flushAll();
                                that.form = {};

                            }

                        })
                    } else {
                        that.$message.error("添加有误");
                    }
                })
            },
            //修改用户信息
            updateUser() {
                var that = this;
                this.$refs.editerRef.validate((valid) => {//判断表单内是否有标红的地方
                    if (valid) {
                        this.$http.post("/system/user/updateUserByUser", this.updateUserFormData).then(function (resp) {
                            if (resp.data.code === 200) {
                                that.$message.success(resp.data.msg);
                                that.initTable();
                            } else {
                                that.$message.error(resp.data.msg);

                            }
                            that.updateUserDialog = false;
                        })
                    } else {
                        that.$message.error("修改有误");
                    }
                })
            },


            //加载表格数据
            initTable() {
                this.$http.post("/system/user/getUserByPage/" + this.currentPage + "/" + this.pageSize, this.formData).then(result => {
                    if (result.data.code == 200) {
                        //  console.log(result)
                        this.tableData = result.data.data.records;
                        this.total = result.data.data.total;
                    }
                })
            },

            //关闭时清空表单
            flushAll() {
                this.$refs.formLabel.resetFields();
            },
            // 重置查询条件
            handleReset() {
                this.reload()
            },
            // 刷新当前页面
            reload() {
                this.formData = {}
                this.initTable()
            },
            //关闭时清空表单
            closeUpdateUser() {
                this.$refs.editerRef.resetFields();
                this.initTable();
            },

        //搜索按钮
        findUserBySouSuo() {
            this.currentPage=1;
            this.initTable();
        },


            //分页
            handleSizeChange(val) {
                this.pageSize = val;
                this.initTable();
            },
            //分页按钮被点击，发生改变时
            handleCurrentChange(val) {
                this.currentPage = val;
                this.initTable();
            },


            //根据传入的id与转态修改用户状态
            changeStatus(id, deleted) {
                const title = {0: '启用', 1: '禁用'}
                this.$confirm(`确定要${title[deleted]}该用户吗?`, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var that = this;
                    this.$http.post(`/system/user/updateUserStatusByid/${id}/${deleted}`).then(function (resp) {
                        if (resp.data.code === 200) {
                            that.$message.success(resp.data.msg);
                            that.initTable();
                        } else {
                            that.$message.error('${title[deleted]}' + resp.data.msg);
                        }
                    })
                    this.reload()
                }).catch(() => {
                    this.reload()
                })
            }
        }

    }
</script>

<style>


    .el-table th.gutter {
        display: table-cell !important;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
